﻿using CCWin;
using SuperMap.Data;
using SuperMap.Mapping;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace MDF
{
    public partial class SJPP : CCSkinMain
    {
        
        private SJPPXZYS m_xzys;
        private IO_xml m_Xml;
        private Map[] m_Maps;
        private Datasources m_datasources;
        private DataInfo m_dataInfo;
        private List<DatasetVector[]> m_SetToSets;
        private CancellationTokenSource m_Cancellation;
        //阈值配置文件读取参数
        private string m_infoName;
        private string[] m_keys;
        private string m_andStr;
        /// <summary>
        /// 存储选择集名称
        /// </summary>
        public string selectName;
        /// <summary>
        /// 静态控制窗体展示
        /// </summary>
        public static SJPP m_sjpp;

        /// <summary>
        /// 数据匹配初始化（选择集）
        /// </summary>
        /// /// <param name="maps">已打开地图名称集合</param>
        /// /// <param name="datasources">数据源集合</param>
        public SJPP(Map[] maps, Datasources datasources)
        {
            InitializeComponent();

            m_Maps = maps;
            m_datasources = datasources;
            m_dataInfo = new DataInfo(datasources);
            //静态窗体控制
            m_sjpp = this;
            
        }
        /// <summary>
        /// 数据匹配初始化（数据集）
        /// </summary>
        /// <param name="datasources">数据源集合</param>
        public SJPP(Datasources datasources)
        {
            InitializeComponent();

            m_datasources = datasources;
            m_dataInfo = new DataInfo(datasources);
            //优化填充控件
            HideControls();
        }

        /// <summary>
        /// 根据窗体创建对应的xml实例
        /// </summary>
        public void Crate_m_Xml()
        {
            try
            {
                switch (this.Name)
                {
                    case "KJPP":
                        m_Xml = new IO_xml("PiPeiYuZhi");
                        m_infoName = "KongJianYuZhi";
                        m_andStr = "..";
                        m_keys = new string[] { "DistanceThershold", "LengthThershold" };
                        break;
                    case "TPPP":
                        m_Xml = new IO_xml("PiPeiYuZhi");
                        m_infoName = "TuoPuYuZhi";
                        m_andStr = "...";
                        m_keys = new string[] { "ErrorThershold", "ToleranceThershold", "DepthThershold" };
                        break;
                    case "SXPP":
                        m_Xml = new IO_xml("ShuXingPiPei");
                        m_infoName = "YingSheInfo";
                        m_andStr = "..";
                        m_keys = new string[] { };
                        break;
                    default:
                        //无
                        break;
                }
            }
            catch (Exception)
            {

                throw;
            }
        }
        /// <summary>
        /// 填充数据集信息
        /// </summary>
        public void FillSets()
        {
            try
            {
                //选择集填充
                if (this.Text.Equals("选择集匹配"))
                {
                    //先清空
                    this.Set1_Combo.Items.Clear();
                    this.Set2_Combo.Items.Clear();
                    //获取选择集信息
                    string[] selectionsNames = m_dataInfo.GetAllSelectionsNames();
                    foreach(string selectionsName in selectionsNames)
                    {
                        this.Set1_Combo.Items.Add(selectionsName);
                        this.Set2_Combo.Items.Add(selectionsName);
                    }
                    if (this.Set1_Combo.Items.Count > 0)
                    {
                        //默认选择第一项，并填充表数据
                        this.Set1_Combo.SelectedIndex = 0;
                        //第二下拉框就移除对应项
                        this.Set2_Combo.Items.RemoveAt(0);
                        //获取选择集信息并填充
                        this.Set1_TextBox.Text = m_dataInfo.GetSelectionsInfo(this.Set1_Combo.Text);
                        if (this.Set2_Combo.Items.Count > 0)
                        {
                            this.Set2_Combo.SelectedIndex = 0;
                            //获取选择集信息并填充
                            this.Set2_TextBox.Text = m_dataInfo.GetSelectionsInfo(this.Set2_Combo.Text);
                        }
                    }
                }
                //数据集的填充
                else
                {
                    foreach (Datasource datasource in m_datasources)
                    {
                        foreach (Dataset dataset in datasource.Datasets)
                        {
                            this.Set1_Combo.Items.Add(dataset.Name);
                            this.Set2_Combo.Items.Add(dataset.Name);
                        }
                    }
                    if(this.Set1_Combo.Items.Count > 0)
                    {
                        //默认选择第一项
                        this.Set1_Combo.SelectedIndex = 0;
                        this.Set2_Combo.Items.RemoveAt(0);
                        //获取数据集信息并填充
                        this.Set1_TextBox.Text = m_dataInfo.GetDatasetsInfo(this.Set1_Combo.Text, m_infoName, m_andStr);
                        if (this.Set2_Combo.Items.Count > 0)
                        {
                            this.Set2_Combo.SelectedIndex = 0;
                            //获取数据集信息并填充
                            this.Set2_TextBox.Text = m_dataInfo.GetDatasetsInfo(this.Set2_Combo.Text, m_infoName, m_andStr);
                        }
                    }
                }
            }
            catch (Exception)
            {

                throw;
            }
        }
        /// <summary>
        /// 调整数据集窗体控件展示，隐藏非必要控件
        /// </summary>
        private void HideControls()
        {
            try
            {
                this.Text = "数据集匹配";
                this.Set1_Label.Text = "数据集1";
                this.Set2_Label.Text = "数据集2";
                this.Crate_Button.Dispose();
                this.Delete_Button.Dispose();
            }
            catch (Exception)
            {

                throw;
            }
        }

        /// <summary>
        /// 创建新的选择集
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Crate_Button_Click(object sender, EventArgs e)
        {
            try
            {
                if (m_xzys == null || m_xzys.IsDisposed)
                {
                    //创建窗口
                    m_xzys = new SJPPXZYS(m_Maps);
                    m_xzys.Show();
                    
                }
                else
                {
                    m_xzys.Activate();
                }
            }
            catch (Exception)
            {

                throw;
            }
        }
        /// <summary>
        /// 删除选择集
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Delete_Button_Click(object sender, EventArgs e)
        {
            try
            {
                string Tishi = "是否删除选择集1中:" + this.Set1_Combo.Text + "选择集？";
                if (MessageBox.Show(Tishi, "提示：",MessageBoxButtons.OKCancel) == DialogResult.OK)
                {
                    if(m_dataInfo.DeleteSelectionsInfo(this.Set1_Combo.Text))
                    {
                        MessageBox.Show("删除成功！", "提示：");
                    }
                    else
                    {
                        MessageBox.Show("删除失败！", "提示：");
                    }
                }
            }
            catch (Exception)
            {

                throw;
            }
        }
        /// <summary>
        /// 选择后修改可选项1
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Set1_Combo_SelectionChangeCommitted(object sender, EventArgs e)
        {
            try
            {
                ComboBox m_ComboBox = (ComboBox)sender;
                //获取选择项
                string text1 = m_ComboBox.Text;
                //填充信息
                if (this.Text.Equals("选择集匹配"))
                {
                    //选择集填充
                    this.Set1_TextBox.Text = m_dataInfo.GetSelectionsInfo(text1);
                }
                else
                {
                    //数据集填充
                    this.Set1_TextBox.Text = m_dataInfo.GetDatasetsInfo(text1, m_infoName, m_andStr);
                }
                //判断现选择项是否相同，相同要重置选项（else）
                if (text1 != this.Set2_Combo.Text)
                {
                    //清除后重新填充
                    string text2 = this.Set2_Combo.Text;
                    this.Set2_Combo.Items.Clear();
                    //获取填充列表
                    List<object> Items = new List<object>();
                    foreach (var item in this.Set1_Combo.Items)
                    {
                        Items.Add(item);
                    }
                    this.Set2_Combo.Items.AddRange(Items.ToArray());

                    this.Set2_Combo.Items.Remove(text1);
                    //恢复原选项
                    this.Set2_Combo.Text = text2;
                }
                else
                {
                    //清除后重新填充
                    this.Set2_Combo.Items.Clear();
                    //获取填充列表
                    List<object> Items = new List<object>();
                    foreach (var item in this.Set1_Combo.Items)
                    {
                        Items.Add(item);
                    }
                    this.Set2_Combo.Items.AddRange(Items.ToArray());
                    this.Set2_Combo.Items.Remove(text1);
                    //重置为默认选择项
                    if (this.Set2_Combo.Items.Count > 0)
                    {
                        this.Set2_Combo.SelectedIndex = 0;
                        //填充信息
                        if (this.Text.Equals("选择集匹配"))
                        {
                            //选择集填充
                            this.Set2_TextBox.Text = m_dataInfo.GetSelectionsInfo(this.Set2_Combo.Text);
                        }
                        else
                        {
                            //数据集填充
                            this.Set2_TextBox.Text = m_dataInfo.GetDatasetsInfo(this.Set2_Combo.Text, m_infoName, m_andStr);
                        }
                    }
                }
                //重新检查
                this.Yes_Button.Enabled = false;

            }
            catch (Exception)
            {

                throw;
            }
        }
        /// <summary>
        /// 选择后修改可选项2
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Set2_Combo_SelectionChangeCommitted(object sender, EventArgs e)
        {
            try
            {
                //填充基本信息
                if (this.Text.Equals("选择集匹配"))
                {
                    //选择集填充
                    this.Set2_TextBox.Text = m_dataInfo.GetSelectionsInfo(this.Set2_Combo.Text);
                }
                else
                {
                    //数据集填充
                    this.Set2_TextBox.Text = m_dataInfo.GetDatasetsInfo(this.Set2_Combo.Text, m_infoName, m_andStr);
                }
                //重新检查
                this.Yes_Button.Enabled = false;
            }
            catch (Exception)
            {

                throw;
            }
        }

        #region 检查
        /// <summary>
        /// 检查是否合法
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Check_Button_Click(object sender, EventArgs e)
        {
            try
            {
                //检查数据是否合法：类型一致性、非空、是否设定阈值
                //结果记录
                StringBuilder stringBuilder = new StringBuilder();
                //选择集检查
                if (this.Text.Equals("选择集匹配"))
                {
                    //获取选择集信息
                    List<string[]> selections1 = m_dataInfo.GetSelectionSetsInfo(this.Set1_Combo.Text);
                    List<string[]> selections2 = m_dataInfo.GetSelectionSetsInfo(this.Set2_Combo.Text);
                    //获取数据集类型信息
                    List<DatasetVector> datasetVector1s = new List<DatasetVector>();
                    List<DatasetVector> datasetVector2s = new List<DatasetVector>();
                    foreach (string[] setInfo in selections1)
                    {
                        //判断当前的数据源是否有对应数据
                        if (m_datasources[setInfo[1]] != null)
                        {
                            if (m_datasources[setInfo[1]].Datasets[setInfo[0]] != null)
                            {
                                datasetVector1s.Add(m_datasources[setInfo[1]].Datasets[setInfo[0]] as DatasetVector);
                            }
                            else
                            {
                                MessageBox.Show("当前数据源缺少数据集：" + setInfo[0], "警告：");
                            }
                        }
                        else
                        {
                            MessageBox.Show("当前缺少数据源：" + setInfo[1], "警告：");
                        }
                    }
                    foreach (string[] setInfo in selections2)
                    {
                        //判断当前的数据源是否有对应数据
                        if (m_datasources[setInfo[1]] != null)
                        {
                            if (m_datasources[setInfo[1]].Datasets[setInfo[0]] != null)
                            {
                                datasetVector2s.Add(m_datasources[setInfo[1]].Datasets[setInfo[0]] as DatasetVector);
                            }
                            else
                            {
                                MessageBox.Show("当前数据源缺少数据集：" + setInfo[0], "警告：");
                            }
                        }
                        else
                        {
                            MessageBox.Show("当前缺少数据源：" + setInfo[1], "警告：");
                        }
                    }
                    //判断数据集类型是否一致，展示结果信息
                    if (datasetVector1s.Count != 0 && datasetVector2s.Count != 0)
                    {
                        string result = CheckSet(datasetVector1s, datasetVector2s);
                        MessageBox.Show(result, "提示：");
                    }
                    else
                    {
                        MessageBox.Show("检查完成", "提示：");
                    }

                }
                //数据集检查
                else
                {
                    //遍历数据源，获取数据集类型信息
                    List<DatasetVector> datasetVector1s = new List<DatasetVector>();
                    List<DatasetVector> datasetVector2s = new List<DatasetVector>();
                    foreach (Datasource datasource in m_datasources)
                    {
                        if (datasource.Datasets[this.Set1_Combo.Text] != null)
                        {
                            datasetVector1s.Add(datasource.Datasets[this.Set1_Combo.Text] as DatasetVector);
                        }
                        if(datasource.Datasets[this.Set2_Combo.Text] != null)
                        {
                            datasetVector2s.Add(datasource.Datasets[this.Set2_Combo.Text] as DatasetVector);
                        }
                    }
                    //判断数据集类型是否一致，展示结果信息
                    if (datasetVector1s.Count != 0 && datasetVector2s.Count != 0)
                    {
                        string result = CheckSet(datasetVector1s, datasetVector2s);
                        MessageBox.Show(result, "提示：");
                    }
                    else
                    {
                        MessageBox.Show("检查完成", "提示：");
                    }
                }
            }
            catch (Exception)
            {

                throw;
            }
        }
        /// <summary>
        /// 检查数据类型是否一致
        /// </summary>
        /// <param name="datasetVector1s">数据集1类型列表</param>
        /// <param name="datasetVector2s">数据集2类型列表</param>
        /// <returns>完全匹配返回1，部分匹配返回-1，不匹配返回0</returns>
        private string CheckSet(List<DatasetVector> datasetVector1s, List<DatasetVector> datasetVector2s)
        {
            //记录结果信息
            string result = "";
            //统计总共有多少个数据集
            int count = datasetVector1s.Count + datasetVector2s.Count;
            //实例化 数据集对 列表
            m_SetToSets = new List<DatasetVector[]>();
            //匹配类型的相同的数据集
            foreach (DatasetVector setVector1 in datasetVector1s)
            {
                foreach (DatasetVector setVector2 in datasetVector2s)
                {
                    if (setVector1.Type == setVector2.Type)
                    {
                        //匹配后检查阈值信息或者映射信息
                        if (this.Name != "SXPP")
                        {
                            //检查阈值
                            result = CheckYuZhiInfo(setVector1.Name, setVector2.Name);
                            if(this.Name == "TPPP" && setVector1.Type == DatasetType.Point)
                            {
                                result += CheckLinkInfo(setVector1.Name);
                                result += CheckLinkInfo(setVector2.Name);
                            }
                        }
                        else
                        {
                            //检查映射
                            result = CheckYingSheInfo(setVector1.Name, setVector2.Name);
                        }

                        //检查后记录配对信息
                        m_SetToSets.Add(new DatasetVector[] { setVector1, setVector2 });
                    }
                }
            }
            //删除匹配好的数据集,来判断选择据是否完全匹配
            foreach (DatasetVector[] setVectors in m_SetToSets)
            {
                if (datasetVector1s.Contains(setVectors[0]))
                {
                    datasetVector1s.Remove(setVectors[0]);
                }
                if (datasetVector2s.Contains(setVectors[1]))
                {
                    datasetVector2s.Remove(setVectors[1]);
                }
            }
            //判断结果
            if (datasetVector1s.Count + datasetVector2s.Count == 0)
            {
                this.Yes_Button.Enabled = true;
                result = "检查完成！\n" + result;
                //返回结果,完全匹配
                return result;
            }
            else if (datasetVector1s.Count + datasetVector2s.Count < count)
            {
                this.Yes_Button.Enabled = true;
                result = "选择集合中数据集未能完全配对！\n但您仍可以继续计算已配对数据集！\n" + result;
                //返回结果，部分匹配
                return result;
            }
            else
            {
                this.Yes_Button.Enabled = false;
                result = "当前数据选择不合法！\n数据集合中无相互对应类型数据存在！\n" + result;
                //返回结果，不匹配
                return result;
            }
        }
        /// <summary>
        /// 检查阈值信息
        /// </summary>
        /// <param name="set1Name">数据集1的名称</param>
        /// <param name="set2Name">数据集2的名称</param>
        /// <returns>返回对结果的描述字符串</returns>
        private string CheckYuZhiInfo(string set1Name, string set2Name)
        {
            try
            {
                //数据节点名称为两个数据的名称
                string dataName = set1Name + m_andStr + set2Name;
                string dataNameRe = set2Name + m_andStr + set1Name;
                //查询是否有阈值信息
                if (m_Xml.ReadValueByKey(dataName, m_keys[0]) == null && m_Xml.ReadValueByKey(dataNameRe, m_keys[0]) == null)
                {
                    //没有则打开阈值窗口进行创建，实例化阈值窗体
                    if (MessageBox.Show("您需要创建阈值信息：" + set1Name + "<>" + set2Name, "提示：", MessageBoxButtons.OKCancel) == DialogResult.OK)
                    {
                        SJPPYZ m_sJPPYZ = new SJPPYZ();
                        m_sJPPYZ.Name = "KJPPYZ";
                        if (this.Name == "TPPP")
                        {
                            m_sJPPYZ.Name = "TPPPYZ";
                            //变更阈值窗体形式
                            m_sJPPYZ.ChangeForm();
                        }
                        m_sJPPYZ.Ban_ChangeSelections(set1Name, set2Name);
                        DialogResult dialogResult = m_sJPPYZ.ShowDialog();
                        m_sJPPYZ.Dispose();
                        if (dialogResult != DialogResult.OK)
                        {
                            return "有未设置阈值的数据集";
                        }
                        else
                        {
                            //刷新一下xml读取信息
                            Crate_m_Xml();
                            return "";
                        }
                    }
                    else
                    {
                        return "有未设置阈值的数据集";
                    }
                }
                else
                {
                    return "";
                }
            }
            catch (Exception)
            {

                throw;
            }
        }
        /// <summary>
        /// 检查链接信息
        /// </summary>
        /// <param name="setName">数据集1的名称</param>
        /// <returns></returns>
        private string CheckLinkInfo(string setName)
        {
            try
            {
                //查询是否有链接信息
                if (m_Xml.ReadValues("TuoPuLink",setName).Length == 0)
                {
                    //没有则打开链接窗口进行创建，实例化链接窗体
                    if (MessageBox.Show("您需要创建链接信息：点数据集--" + setName, "", MessageBoxButtons.OKCancel) == DialogResult.OK)
                    {
                        TPPPLJ m_TPPPLJ = new TPPPLJ(m_datasources);
                        m_TPPPLJ.ChangeCobomText(setName);
                        DialogResult dialogResult = m_TPPPLJ.ShowDialog();
                        m_TPPPLJ.Dispose();
                        if (dialogResult != DialogResult.OK)
                        {
                            return "有未设置阈值的数据集";
                        }
                        else
                        {
                            //刷新一下xml读取信息
                            Crate_m_Xml();
                            return "";
                        }
                    }
                    else
                    {
                        return "有未设置阈值的数据集";
                    }
                }
                else
                {
                    return "";
                }
            }
            catch (Exception)
            {

                throw;
            }
        }
        /// <summary>
        /// 检查映射信息
        /// </summary>
        /// <param name="set1Name">数据集1的名称</param>
        /// <param name="set2Name">数据集2的名称</param>
        /// <returns>返回对结果的描述字符串</returns>
        private string CheckYingSheInfo(string set1Name, string set2Name)
        {
            try
            {
                //数据节点名称为两个数据的名称
                string dataName = set1Name + m_andStr + set2Name;
                string dataNameRe = set2Name + m_andStr + set1Name;
                //判断是否存在映射信息
                if (m_Xml.ReadChildNodesName(dataName).Length == 0 && m_Xml.ReadChildNodesName(dataNameRe).Length == 0)
                {
                    //不存在时，询问是否创建
                    if (MessageBox.Show("当前数据集不存在映射信息，是否创建？", "提示：", MessageBoxButtons.OKCancel) == DialogResult.OK)
                    {
                        //创建映射
                        SXPPYS m_sXPPYS = new SXPPYS(m_datasources);
                        //填充窗体控件
                        m_sXPPYS.Change_ComboBox(set1Name, set2Name);
                        DialogResult dialogResult = m_sXPPYS.ShowDialog();
                        m_sXPPYS.Dispose();
                        if (dialogResult != DialogResult.OK)
                        {
                            return "有未建立映射的数据集";
                        }
                        else
                        {
                            //刷新一下xml读取信息
                            Crate_m_Xml();
                            return "";
                        }
                    }
                    else
                    {
                        return "";
                    }
                }
                else
                {
                    return "";
                }
            }
            catch (Exception)
            {

                throw;
            }
        }

        #endregion
        #region 执行匹配，或者退出
        /// <summary>
        /// 按照设置参数，执行对应匹配，并保存结果
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Yes_Button_Click(object sender, EventArgs e)
        {
            try
            {
                switch (this.Name)
                {
                    case "KJPP":
                        //进行几何匹配并把结果，传给主窗体（全程序变量）
                        List<DatasetsMatchResult> MatchSpaceResults = RunMatchingSpace();
                        foreach (DatasetsMatchResult result in MatchSpaceResults)
                        {
                            MDF_Main.mDF_Main.DatasetsMatchResultAdd(result);
                        }
                        if (MatchSpaceResults.Count > 0)
                        {
                            //有结果则初始化窗体
                            RefreshSetings();
                            MessageBox.Show("计算成功！", "提示：");
                        }
                        else
                        {
                            //没有结果则反馈
                            MessageBox.Show("计算失败！", "提示：");
                        }
                        break;
                    case "SXPP":
                        //进行属性匹配并把结果，传给主窗体（全程序变量）
                        List<DatasetsMatchResult> MatchAttributeResults = RunMatchingAttribute();
                        foreach (DatasetsMatchResult result in MatchAttributeResults)
                        {
                            MDF_Main.mDF_Main.DatasetsMatchResultAdd(result);
                        }
                        if (MatchAttributeResults.Count > 0)
                        {
                            //有结果则初始化窗体
                            RefreshSetings();
                            MessageBox.Show("计算成功！", "提示：");
                        }
                        else
                        {
                            //没有结果则反馈
                            MessageBox.Show("计算失败！", "提示：");
                        }
                        break;
                    case "TPPP":
                        //进行几何匹配并把结果，传给主窗体（全程序变量）
                        List<DatasetsMatchResult> MatchTopologyResults = RunMatchingTopology();
                        foreach (DatasetsMatchResult result in MatchTopologyResults)
                        {
                            MDF_Main.mDF_Main.DatasetsMatchResultAdd(result);
                        }
                        if (MatchTopologyResults.Count > 0)
                        {
                            //有结果则初始化窗体
                            RefreshSetings();
                            MessageBox.Show("计算成功！", "提示：");
                        }
                        else
                        {
                            //没有结果则反馈
                            MessageBox.Show("计算失败！", "提示：");
                        }
                        break;
                    default:
                        break;
                }

            }
            catch (Exception)
            {

                throw;
            }
        }
        /// <summary>
        /// 执行几何匹配
        /// </summary>
        /// <returns>返回数据集匹配的结果信息。详情参考DatasetsMatchResult类</returns>
        private List<DatasetsMatchResult> RunMatchingSpace()
        {
            try
            {
                //初始化数据计算总量
                StartValueSum();
                //保存对应匹配集的信息列表
                List<DatasetsMatchResult> datasetsMatchResults = new List<DatasetsMatchResult>();
                //实例化执行几何匹配的对象,和任务控制对象
                MatchSpace matchSpace = new MatchSpace(true);
                m_Cancellation = new CancellationTokenSource();
                //遍历检查后的数据集合
                foreach (DatasetVector[] setToset in m_SetToSets)
                {
                    //获取数据集相关阈值信息
                    double[] yuzhi = GetYuZhi(setToset[0].Name, setToset[1].Name);
                    if (yuzhi.Length != 0)
                    {
                        //判断数据类型
                        if (setToset[0].Type == DatasetType.Point)
                        {
                            //保存结果
                            List<double[]> matchSpaceResult;
                            if (this.Text.Equals("选择集匹配"))
                            {
                                //获取id数组
                                int[] set1IDs = m_dataInfo.GetSelectionDataIDs(this.Set1_Combo.Text, setToset[0].Name);
                                int[] set2IDs = m_dataInfo.GetSelectionDataIDs(this.Set2_Combo.Text, setToset[1].Name);
                                //获取点记录集
                                Recordset point1 = setToset[0].Query(set1IDs, CursorType.Static);
                                Recordset point2 = setToset[1].Query(set2IDs, CursorType.Static);
                                //进行几何匹配
                                Task<List<double[]>> task = new Task<List<double[]>>(() => matchSpace.MatchDataPoint1(point1, point2, yuzhi[0], setToset[0].PrjCoordSys.CoordUnit, m_Cancellation.Token), m_Cancellation.Token);
                                task.Start();
                                ProgressForm progressForm = new ProgressForm(this.Set1_Combo.Text + "<>"+ this.Set2_Combo.Text);
                                progressForm.Text = "KJPP";
                                if (progressForm.ShowDialog() != DialogResult.OK)
                                {
                                    m_Cancellation.Cancel();
                                    MessageBox.Show("已取消！");
                                }
                                matchSpaceResult = task.Result;
                                //释放记录集
                                point1.Dispose();
                                point2.Dispose();
                                progressForm.Dispose();


                            }
                            else
                            {
                                //获取点记录集
                                Recordset point1 = setToset[0].GetRecordset(false, CursorType.Static);
                                Recordset point2 = setToset[1].GetRecordset(false, CursorType.Static);
                                //进行几何匹配
                                Task<List<double[]>> task = new Task<List<double[]>>(() => matchSpace.MatchDataPoint1(point1, point2, yuzhi[0], setToset[0].PrjCoordSys.CoordUnit, m_Cancellation.Token), m_Cancellation.Token);
                                task.Start();
                                ProgressForm progressForm = new ProgressForm(setToset[0].Name + "<>" + setToset[1].Name);
                                progressForm.Text = "KJPP";
                                if (progressForm.ShowDialog() != DialogResult.OK)
                                {
                                    m_Cancellation.Cancel();
                                    MessageBox.Show("已取消！");
                                }
                                matchSpaceResult = task.Result;
                                //释放记录集
                                point1.Dispose();
                                point2.Dispose();
                                progressForm.Dispose();
                            }
                            if (matchSpaceResult != null)
                            {
                                //保存对应匹配集的结果信息
                                datasetsMatchResults.Add(new DatasetsMatchResult()
                                {
                                    Set1Name = setToset[0].Name,
                                    Set2Name = setToset[1].Name,
                                    MatchSpaceResult = matchSpaceResult
                                });
                            }
                        }
                        else if (setToset[0].Type == DatasetType.Line)
                        {
                            //保存结果
                            List<double[]> matchSpaceResult;
                            if (this.Text.Equals("选择集匹配"))
                            {
                                //获取id数组
                                int[] set1IDs = m_dataInfo.GetSelectionDataIDs(this.Set1_Combo.Text, setToset[0].Name);
                                int[] set2IDs = m_dataInfo.GetSelectionDataIDs(this.Set2_Combo.Text, setToset[1].Name);
                                //获取线记录集
                                Recordset line1 = setToset[0].Query(set1IDs, CursorType.Static);
                                Recordset line2 = setToset[1].Query(set2IDs, CursorType.Static);
                                //进行几何匹配
                                Task<List<double[]>> task = new Task<List<double[]>>(() => matchSpace.MatchDataLine(line1, line2, yuzhi[0], yuzhi[1], setToset[0].PrjCoordSys.CoordUnit, m_Cancellation.Token), m_Cancellation.Token);
                                task.Start();
                                ProgressForm progressForm = new ProgressForm(this.Set1_Combo.Text + "<>" + this.Set2_Combo.Text);
                                progressForm.Text = "KJPP";
                                if (progressForm.ShowDialog() != DialogResult.OK)
                                {
                                    m_Cancellation.Cancel();
                                    MessageBox.Show("已取消！");
                                }
                                matchSpaceResult = task.Result;
                                //释放记录集
                                line1.Dispose();
                                line1.Dispose();
                                progressForm.Dispose();
                            }
                            else
                            {
                                //获取线记录集
                                Recordset line1 = setToset[0].GetRecordset(false, CursorType.Static);
                                Recordset line2 = setToset[1].GetRecordset(false, CursorType.Static);
                                //进行几何匹配
                                Task<List<double[]>> task = new Task<List<double[]>>(() => matchSpace.MatchDataLine(line1, line2, yuzhi[0], yuzhi[1], setToset[0].PrjCoordSys.CoordUnit, m_Cancellation.Token), m_Cancellation.Token);
                                task.Start();
                                ProgressForm progressForm = new ProgressForm(setToset[0].Name + "<>" + setToset[1].Name);
                                progressForm.Text = "KJPP";
                                if (progressForm.ShowDialog() != DialogResult.OK)
                                {
                                    m_Cancellation.Cancel();
                                    MessageBox.Show("已取消！");
                                }
                                matchSpaceResult = task.Result;
                                //释放记录集
                                line1.Dispose();
                                line1.Dispose();
                                progressForm.Dispose();
                            }
                            if (matchSpaceResult != null)
                            {
                                //保存对应匹配集的结果信息
                                datasetsMatchResults.Add(new DatasetsMatchResult()
                                {
                                    Set1Name = setToset[0].Name,
                                    Set2Name = setToset[1].Name,
                                    MatchSpaceResult = matchSpaceResult
                                });
                            }
                        }
                        else
                        {
                            MessageBox.Show("格式内容似乎出了点问题，无法计算~\n当前仅支持二维点、线计算。", "警告：");
                        }
                    }
                    else
                    {
                        MessageBox.Show("数据集未设置阈值：" + setToset[0].Name + ":" + setToset[1].Name, "警告：");
                    }

                }
                //返回结果
                return datasetsMatchResults;
            }
            catch (Exception)
            {

                throw;
            }
        }
        /// <summary>
        /// 执行属性匹配
        /// </summary>
        /// <returns>返回数据集匹配的结果信息。详情参考DatasetsMatchResult类</returns>
        private List<DatasetsMatchResult> RunMatchingAttribute()
        {
            try
            {
                //初始化数据计算总量
                StartValueSum();
                //保存对应匹配集的信息列表
                List<DatasetsMatchResult> datasetsMatchResults = new List<DatasetsMatchResult>();
                //实例化属性匹配对象
                MatchAttribute matchAttribute = new MatchAttribute(true);
                m_Cancellation = new CancellationTokenSource();
                //遍历检查后的数据集合
                foreach (DatasetVector[] setToset in m_SetToSets)
                {
                    //获取数据集映射信息
                    List<string[]> fieldInfos = GetFieldInfos(setToset[0].Name, setToset[1].Name);
                    //获取同义词集
                    List<string[]> sameSets = new List<string[]>();
                    IO_xml xml = new IO_xml("ShuXingZiDian");
                    string[] sameSetNames = xml.ReadChildNodesName("SynSet");
                    foreach (string name in sameSetNames)
                    {
                        sameSets.Add(xml.ReadInnerText(name).Split('_'));
                    }
                    //保存结果
                    List<double[]> matchAttributeResult;
                    if (this.Text.Equals("选择集匹配"))
                    {
                        //获取id数组
                        int[] set1IDs = m_dataInfo.GetSelectionDataIDs(this.Set1_Combo.Text, setToset[0].Name);
                        int[] set2IDs = m_dataInfo.GetSelectionDataIDs(this.Set2_Combo.Text, setToset[1].Name);
                        //获取记录集
                        Recordset reSet1 = setToset[0].Query(set1IDs, CursorType.Static);
                        Recordset reSet2 = setToset[1].Query(set2IDs, CursorType.Static);
                        //进行属性匹配
                        Task<List<double[]>> task = new Task<List<double[]>>(() => matchAttribute.MatchDataset(reSet1, reSet2, fieldInfos, sameSets, m_Cancellation.Token), m_Cancellation.Token);
                        task.Start();
                        ProgressForm progressForm = new ProgressForm(this.Set1_Combo.Text + "<>" + this.Set2_Combo.Text);
                        progressForm.Text = "SXPP";
                        if (progressForm.ShowDialog() != DialogResult.OK)
                        {
                            m_Cancellation.Cancel();
                            MessageBox.Show("已取消！");
                        }
                        matchAttributeResult = task.Result;
                        //释放记录集
                        reSet1.Dispose();
                        reSet1.Dispose();
                        progressForm.Dispose();
                    }
                    else
                    {
                        //获取记录集
                        Recordset reSet1 = setToset[0].GetRecordset(false, CursorType.Static);
                        Recordset reSet2 = setToset[1].GetRecordset(false, CursorType.Static);
                        //进行属性匹配
                        Task<List<double[]>> task = new Task<List<double[]>>(() => matchAttribute.MatchDataset(reSet1, reSet2, fieldInfos, sameSets, m_Cancellation.Token), m_Cancellation.Token);
                        task.Start();
                        ProgressForm progressForm = new ProgressForm(setToset[0].Name + "<>" + setToset[1].Name);
                        progressForm.Text = "SXPP";
                        if (progressForm.ShowDialog() != DialogResult.OK)
                        {
                            m_Cancellation.Cancel();
                            MessageBox.Show("已取消！");
                        }
                        matchAttributeResult = task.Result;
                        //释放记录集
                        reSet1.Dispose();
                        reSet1.Dispose();
                        progressForm.Dispose();
                    }
                    if (matchAttributeResult != null)
                    {
                        //保存对应匹配集的结果信息
                        datasetsMatchResults.Add(new DatasetsMatchResult()
                        {
                            Set1Name = setToset[0].Name,
                            Set2Name = setToset[1].Name,
                            MatchAttributeResult = matchAttributeResult,
                            MatchAttributeFieldResult = matchAttribute.FieldResult
                        });
                    }
                }
                //返回结果
                return datasetsMatchResults;
            }
            catch (Exception)
            {

                throw;
            }
        }
        /// <summary>
        /// 执行拓扑匹配
        /// </summary>
        /// <returns>返回数据集匹配的结果信息。详情参考DatasetsMatchResult类</returns>
        private List<DatasetsMatchResult> RunMatchingTopology()
        {
            try
            {
                //初始化数据计算总量
                StartValueSum();
                //保存对应匹配集的信息列表
                List<DatasetsMatchResult> datasetsMatchResults = new List<DatasetsMatchResult>();
                //实例化拓扑匹配对象(默认用第一个数据源)
                MatchTopology matchTopology = new MatchTopology(m_datasources[0], true);
                m_Cancellation = new CancellationTokenSource();
                //遍历检查后的数据集合
                foreach (DatasetVector[] setToset in m_SetToSets)
                {
                    //获取数据集相关阈值信息
                    double[] yuzhi = GetYuZhi(setToset[0].Name, setToset[1].Name);
                    if (yuzhi.Length != 0)
                    {
                        if (setToset[0].Type == DatasetType.Point)
                        {
                            //保存结果
                            List<double[]> matchTopologyResult;
                            if (this.Text.Equals("选择集匹配"))
                            {
                                //获取id数组
                                int[] set1IDs = m_dataInfo.GetSelectionDataIDs(this.Set1_Combo.Text, setToset[0].Name);
                                int[] set2IDs = m_dataInfo.GetSelectionDataIDs(this.Set2_Combo.Text, setToset[1].Name);
                                //获取点记录集
                                Recordset point1 = setToset[0].Query(set1IDs, CursorType.Static);
                                Recordset point2 = setToset[1].Query(set2IDs, CursorType.Static);
                                //获取点记录集所需要的线数据集
                                DatasetVector[] linkLines1 = m_dataInfo.GetLinkDatasets(point1.Dataset.Name);
                                DatasetVector[] linkLines2 = m_dataInfo.GetLinkDatasets(point2.Dataset.Name);
                                //进行拓扑匹配
                                Task<List<double[]>> task = new Task<List<double[]>>(() => matchTopology.MatchDataPoint(point1, linkLines1, point2, linkLines2, yuzhi[0], yuzhi[1], (int)yuzhi[2], m_Cancellation.Token), m_Cancellation.Token);
                                task.Start();
                                ProgressForm progressForm = new ProgressForm(this.Set1_Combo.Text + "<>" + this.Set2_Combo.Text);
                                progressForm.Text = "TPPP";
                                if (progressForm.ShowDialog() != DialogResult.OK)
                                {
                                    m_Cancellation.Cancel();
                                    MessageBox.Show("已取消！");
                                }
                                matchTopologyResult = task.Result;
                                //释放记录集
                                point1.Dispose();
                                point2.Dispose();
                                progressForm.Dispose();
                            }
                            else
                            {
                                //获取点记录集
                                Recordset point1 = setToset[0].GetRecordset(false, CursorType.Static);
                                Recordset point2 = setToset[1].GetRecordset(false, CursorType.Static);
                                //获取点记录集所需要的线数据集
                                DatasetVector[] linkLines1 = m_dataInfo.GetLinkDatasets(point1.Dataset.Name);
                                DatasetVector[] linkLines2 = m_dataInfo.GetLinkDatasets(point2.Dataset.Name);
                                //进行拓扑匹配
                                Task<List<double[]>> task = new Task<List<double[]>>(() => matchTopology.MatchDataPoint(point1, linkLines1, point2, linkLines2, yuzhi[0], yuzhi[1], (int)yuzhi[2], m_Cancellation.Token), m_Cancellation.Token);
                                task.Start();
                                ProgressForm progressForm = new ProgressForm(setToset[0].Name + "<>" + setToset[1].Name);
                                progressForm.Text = "TPPP";
                                if (progressForm.ShowDialog() != DialogResult.OK)
                                {
                                    m_Cancellation.Cancel();
                                    MessageBox.Show("已取消！");
                                }
                                matchTopologyResult = task.Result;
                                //释放记录集
                                point1.Dispose();
                                point2.Dispose();
                                progressForm.Dispose();
                            }
                            if (matchTopologyResult != null)
                            {
                                //保存对应匹配集的结果信息
                                datasetsMatchResults.Add(new DatasetsMatchResult()
                                {
                                    Set1Name = setToset[0].Name,
                                    Set2Name = setToset[1].Name,
                                    MatchTopologyResult = matchTopologyResult
                                });
                            }
                        }
                        else if (setToset[0].Type == DatasetType.Line)
                        {
                            //保存结果
                            List<double[]> matchTopologyResult;
                            if (this.Text.Equals("选择集匹配"))
                            {
                                //获取id数组
                                int[] set1IDs = m_dataInfo.GetSelectionDataIDs(this.Set1_Combo.Text, setToset[0].Name);
                                int[] set2IDs = m_dataInfo.GetSelectionDataIDs(this.Set2_Combo.Text, setToset[1].Name);
                                //获取线记录集
                                Recordset line1 = setToset[0].Query(set1IDs, CursorType.Static);
                                Recordset line2 = setToset[1].Query(set2IDs, CursorType.Static);
                                //进行拓扑匹配
                                Task<List<double[]>> task = new Task<List<double[]>>(() => matchTopology.MatchDataLine(line1, line2, yuzhi[0], yuzhi[1], (int)yuzhi[2], m_Cancellation.Token), m_Cancellation.Token);
                                task.Start();
                                ProgressForm progressForm = new ProgressForm(this.Set1_Combo.Text + "<>" + this.Set2_Combo.Text);
                                progressForm.Text = "TPPP";
                                if (progressForm.ShowDialog() != DialogResult.OK)
                                {
                                    m_Cancellation.Cancel();
                                    MessageBox.Show("已取消！");
                                }
                                matchTopologyResult = task.Result;
                                //释放记录集
                                line1.Dispose();
                                line1.Dispose();
                                progressForm.Dispose();
                            }
                            else
                            {
                                //获取线记录集
                                Recordset line1 = setToset[0].GetRecordset(false, CursorType.Static);
                                Recordset line2 = setToset[1].GetRecordset(false, CursorType.Static);
                                //进行拓扑匹配
                                Task<List<double[]>> task = new Task<List<double[]>>(() => matchTopology.MatchDataLine(line1, line2, yuzhi[0], yuzhi[1], (int)yuzhi[2], m_Cancellation.Token), m_Cancellation.Token);
                                task.Start();
                                ProgressForm progressForm = new ProgressForm(setToset[0].Name + "<>" + setToset[1].Name);
                                progressForm.Text = "TPPP";
                                if (progressForm.ShowDialog() != DialogResult.OK)
                                {
                                    m_Cancellation.Cancel();
                                    MessageBox.Show("已取消！");
                                }
                                matchTopologyResult = task.Result;
                                //释放记录集
                                line1.Dispose();
                                line1.Dispose();
                            }
                            if (matchTopologyResult != null)
                            {
                                //保存对应匹配集的结果信息
                                datasetsMatchResults.Add(new DatasetsMatchResult()
                                {
                                    Set1Name = setToset[0].Name,
                                    Set2Name = setToset[1].Name,
                                    MatchTopologyResult = matchTopologyResult
                                });
                            }
                        }
                        else
                        {
                            MessageBox.Show("格式内容似乎出了点问题，无法计算~\n当前仅支持二维点、线计算。", "警告：");
                        }
                    }
                    else
                    {
                        MessageBox.Show("数据集未设置阈值：" + setToset[0].Name + ":" + setToset[1].Name, "警告：");
                    }
                }
                //刷新树视图
                MDF_Main.mDF_Main.RefreshWorkspaceTree();
                //返回结果
                return datasetsMatchResults;
            }
            catch (Exception)
            {

                throw;
            }
        }
        /// <summary>
        /// 获取阈值
        /// </summary>
        /// <param name="set1Name">数据集1的名称</param>
        /// <param name="set2Name">数据集2的名称</param>
        /// <returns></returns>
        private double[] GetYuZhi(string set1Name, string set2Name)
        {
            try
            {
                //数据节点名称为两个数据的名称
                string dataName = set1Name + m_andStr + set2Name;
                string dataNameRe = set2Name + m_andStr + set1Name;
                //判断信息是否存在
                if (m_Xml.ReadValueByKey(dataName, m_keys[0]) != null)
                {
                    List<double> yuzhi = new List<double>();
                    double value1 = double.Parse(m_Xml.ReadValueByKey(dataName, m_keys[0]));
                    double value2 = double.Parse(m_Xml.ReadValueByKey(dataName, m_keys[1]));
                    yuzhi.Add(value1);
                    yuzhi.Add(value2);
                    if (this.Name == "TPPP")
                    {
                        double value3 = double.Parse(m_Xml.ReadValueByKey(dataName, m_keys[2]));
                        yuzhi.Add(value3);
                    }
                    
                    return yuzhi.ToArray();
                }
                else if (m_Xml.ReadValueByKey(dataNameRe, m_keys[0]) != null)
                {
                    List<double> yuzhi = new List<double>();
                    double value1 = double.Parse(m_Xml.ReadValueByKey(dataNameRe, m_keys[0]));
                    double value2 = double.Parse(m_Xml.ReadValueByKey(dataNameRe, m_keys[1]));
                    yuzhi.Add(value1);
                    yuzhi.Add(value2);
                    if (this.Name == "TPPP")
                    {
                        double value3 = double.Parse(m_Xml.ReadValueByKey(dataNameRe, m_keys[2]));
                        yuzhi.Add(value3);
                    }

                    return yuzhi.ToArray();
                }
                else
                {
                    return new double[] { };
                }
            }
            catch (Exception)
            {

                throw;
            }
        }
        /// <summary>
        /// 获取字段信息
        /// </summary>
        /// <param name="set1Name">数据集1的名称</param>
        /// <param name="set2Name">数据集2的名称</param>
        /// <returns></returns>
        private List<string[]> GetFieldInfos(string set1Name, string set2Name)
        {
            try
            {
                //数据节点名称为两个数据的名称
                string dataName = set1Name + m_andStr + set2Name;
                string dataNameRe = set2Name + m_andStr + set1Name;
                //数据集映射信息
                List<string[]> fieldInfos = new List<string[]>();
                //判断信息是否存在
                if (m_Xml.ReadChildValues(dataName).Count > 0)
                {
                    foreach (string[] feildInfo in m_Xml.ReadChildValues(dataName))
                    {
                        fieldInfos.Add(new string[] { feildInfo[1], feildInfo[2] });
                    }
                }
                else if (m_Xml.ReadChildValues(dataNameRe).Count > 0)
                {
                    foreach (string[] feildInfo in m_Xml.ReadChildValues(dataNameRe))
                    {
                        fieldInfos.Add(new string[] { feildInfo[1], feildInfo[2] });
                    }
                }
                return fieldInfos;
            }
            catch (Exception)
            {

                throw;
            }
        }
        /// <summary>
        /// 获取数据集合的数据计算总量
        /// </summary>
        private void StartValueSum()
        {
            try
            {
                //获取数据集合的数据计算总量
                DatasetsMatchResult.SetsRecordCountSum = 0;
                if (this.Text == "选择集匹配")
                {
                    foreach (DatasetVector[] setToset in m_SetToSets)
                    {
                        DatasetsMatchResult.SetsRecordCountSum += m_dataInfo.GetSelectionDataIDs(this.Set1_Combo.Text, setToset[0].Name).Length * m_dataInfo.GetSelectionDataIDs(this.Set2_Combo.Text, setToset[1].Name).Length;
                    }
                }
                else
                {
                    foreach (DatasetVector[] setToset in m_SetToSets)
                    {
                        DatasetsMatchResult.SetsRecordCountSum += setToset[0].RecordCount * setToset[1].RecordCount;
                    }
                }
            }
            catch (Exception)
            {

                throw;
            }
        }
        /// <summary>
        /// 重置参数和控件
        /// </summary>
        private void RefreshSetings()
        {
            try
            {
                //清除检查结果
                m_SetToSets.Clear();
                //关闭执行控件
                this.Yes_Button.Enabled = false;
            }
            catch (Exception)
            {

                throw;
            }
        }
        /// <summary>
        /// 取消并退出
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void No_Button_Click(object sender, EventArgs e)
        {
            try
            {
                //关闭窗体
                this.Close();
            }
            catch (Exception)
            {

                throw;
            }
        }
        /// <summary>
        /// 关闭窗体
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void SJPP_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (m_SetToSets != null )
            {
                if(m_SetToSets.Count != 0)
                {
                    if (MessageBox.Show("当前有为完成的空间匹配，是否要取消并退出？", "提示:", MessageBoxButtons.OKCancel) != DialogResult.OK)
                    {
                        e.Cancel = true;
                    }
                }
            }
        }
        #endregion
    }
}
